package com.darren.framework.filter;

import com.darren.framework.http.CustomRequestWrapper;
import com.darren.framework.utils.Constant;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class CrossDomainFilter implements Filter {

    public CrossDomainFilter() {
        super();
    }

    @Override
    public void init(FilterConfig filterConfig) {

    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpResponse.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE");
        httpResponse.setHeader("Access-Control-Max-Age", "3600");
        httpResponse.setHeader("Access-Control-Allow-Headers", String.format("Origin,X-Requested-With,Content-Type,Accept,Language,%s,%s", Constant.ACCESS_TOKEN, Constant.REFRESH_TOKEN));
        httpResponse.setHeader("Access-Control-Expose-Headers", String.format("Authorization,DateFormat,%s,%s", Constant.ACCESS_TOKEN, Constant.REFRESH_TOKEN));


        //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //处理分页查询页码    开始
        CustomRequestWrapper customRequestWrapper = new CustomRequestWrapper(httpRequest);
        Object paramValue = customRequestWrapper.getParameter("pageNum");
        if (paramValue != null) {//SPRING DATA JPA Pageable 分页 0 是第一页，所以在这里，把 pageNum 减 1
            try {
                Integer pageNum = Integer.parseInt(paramValue.toString());
                pageNum = pageNum < 1 ? 0 : pageNum - 1;
                customRequestWrapper.setParameter("pageNum", pageNum.toString());
            } catch (NumberFormatException e) {
                customRequestWrapper.setParameter("pageNum", "0");
                System.out.println(e.getMessage());
            }
        } else {
            customRequestWrapper.setParameter("pageNum", "0");
        }
        //处理分页查询页码    结束
        //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        chain.doFilter(customRequestWrapper, httpResponse);
//        chain.doFilter(httpRequest, httpResponse);

    }

    @Override
    public void destroy() {
    }

}